package com.wsoft.interceptor;

import com.wsoft.constant.ConfigConstant;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.CommonConfigService;
import com.wsoft.core.service.RedisService;
import com.wsoft.core.vo.ConfigQuery;
import com.wsoft.utils.FileUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 配置文件上传拦截, 拦截大于指定值的
 * @Author z001
 * @Date 2024/10/15 18:24
 */
@Component
public class FileUploadInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;
    @Resource
    private CommonConfigService commonConfigService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            //获取最大请求大小
            Long limit = getTrafficLimit();
            if(null == limit){
                return true;
            }
            for (MultipartFile file : multipartRequest.getFileMap().values()) {
                if (file.getSize() > limit * FileUtil.MB) {
                    Asserts.fail("[oss.illegal.request]");
                    response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "File size exceeds the maximum limit of " + limit + "MB");
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 获取redis中 config表 file 缓存
     * @param configCache
     * @return
     */
    private Long getTrafficLimit(){
        ConfigQuery query = new ConfigQuery();
        query.setCode(ConfigConstant.OSS_CONFIG_FILE);
        Map<String, String> map = commonConfigService.getConfigValue(query);
        Object object = map.get(ConfigConstant.OSS_MAXIMUM_LIMIT);
        if(null == object){
            return null;
        }
        return Long.valueOf(object.toString());
    }
}
